package com.shark.uh.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;

public class PasswordEncryptor {

    private static final String SALT_ALGORITHM = "SHA1PRNG";
    private static final String HASH_ALGORITHM = "SHA-256";

    /**
     * 生成随机盐值
     *
     * @return 随机盐值
     */
    public static String generateSalt() {
        try {
            SecureRandom sr = SecureRandom.getInstance(SALT_ALGORITHM);
            byte[] salt = new byte[16];
            sr.nextBytes(salt);
            return Base64.getEncoder().encodeToString(salt);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("Error generating salt", e);
        }
    }

    /**
     * 使用盐值和密码生成哈希
     *
     * @param password 原始密码
     * @param salt     盐值
     * @return 加密后的哈希值
     */
    public static String hashPassword(String password, String salt) {
        try {
            MessageDigest md = MessageDigest.getInstance(HASH_ALGORITHM);
            md.update(salt.getBytes());
            byte[] hashedPassword = md.digest(password.getBytes());
            return Base64.getEncoder().encodeToString(hashedPassword);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("Error hashing password", e);
        }
    }

    /**
     * 验证密码是否匹配
     *
     * @param originalPassword 用户输入的密码
     * @param storedHash       数据库存储的哈希值
     * @param salt             存储的盐值
     * @return 是否匹配
     */
    public static boolean verifyPassword(String originalPassword, String storedHash, String salt) {
        String hashToVerify = hashPassword(originalPassword, salt);
        return hashToVerify.equals(storedHash);
    }
}
